<?php

class loginController extends Zend_Controller_Action {

	private $connection;

	function is_logged_in () {
  		if (!($_SESSION["id"]) || ($_SESSION["id"] == "") || ($_SESSION["id"] == 0)) {
    	Header("Location: ./login_form.phtml");
    	exit();
  		}
	}

	function clean_input($input) {
  		$clean = array("\\",'<','>','`',':',';','/','(',')','{','}','[',']');
		return str_ireplace($clean,'', $input);
	}

	function login_check ($forms, $connection) {
  		$error = "";
  		$username = $this->clean_input($forms["username"]);
  		$password = $this->clean_input($forms["password"]);
  		if (trim($username) == "") $error .= "<li>Your username is empty.</li>";
  		if (trim($password) == "") $error .= "<li>Your password is empty.</li>";
  		/* from here, do your sql query to query the database to search for existing record with correct username and password */
  		$query = "SELECT USER_NAME, USER_PASS FROM MED_USER WHERE USER_NAME = '".mysql_real_escape_string($username)."' AND USER_PASS = '".mysql_real_escape_string($password)."'";
  		$result = mysql_query($query,  $connection);
  		if(!$result || (mysql_numrows($result) < 1)) {
     		$error = "Invalid username or password";
  		}else
      	{
        	$error = "";
      	}
  		if (trim($error)!="") return $error;
	}

	function login ($forms) {
  		$username = $this->clean_input($forms["username"]);
  		$password = $this->clean_input($forms["password"]);
  		/* do your sql query again, but now returning the id of member */
  		$query = "SELECT USER_DNI FROM MED_USER WHERE USER_NAME = '".mysql_real_escape_string($username)."' AND USER_PASS = '".mysql_real_escape_string($password)."'";
  		$result = mysql_query($query, $this->connection);
		//  $result = mysql_query($query, $GLOBALS['connection']);
  		if(!$result || (mysql_numrows($result) < 1)) {
     		$id = 0;
  		}else
      	{
			$tupla = mysql_fetch_assoc($result);
        	$id = $tupla['USER_DNI'];
      	}
  		return $id;
	}

	public function indexAction() {
	
		//this->view->title = 'Medisoft - Login';
	
		/*
		if ($_POST) {
  			$forms = array('username'=> $_POST['usuario'], 'password'=> $_POST['contrasena']);
  			$error = $this->login_check($forms, $this->connection);
  			if (trim($error)=="") {
	    		$_SESSION["id"] = $this->login($forms);
    			Header("Location: /index.php/index/welcome");*/ /* Redirect validated member *//*
    			exit();
  			} else {
	    		print "Error:$error";
  			}
  		}
	}*/
	//	$this->getLoginForm();
	}
}
